package com.hunantv.mglive.ui.live;

import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.bumptech.glide.util.Util;
import com.hunantv.mglive.R;
import com.hunantv.mglive.common.BaseActivity;
import com.hunantv.mglive.common.BuildConfig;
import com.hunantv.mglive.common.Constant;
import com.hunantv.mglive.common.FormEncodingBuilderEx;
import com.hunantv.mglive.common.MaxApplication;
import com.hunantv.mglive.data.ChatDataModel;
import com.hunantv.mglive.data.GiftDataModel;
import com.hunantv.mglive.data.GiftShowViewDataModel;
import com.hunantv.mglive.data.ResultModel;
import com.hunantv.mglive.data.StarLiveChatModel;
import com.hunantv.mglive.data.StarLiveDataModel;
import com.hunantv.mglive.data.live.ChatData;
import com.hunantv.mglive.data.login.UserInfoData;
import com.hunantv.mglive.data.user.NoticeMessage;
import com.hunantv.mglive.mqtt.data.MqttLastMsgData;
import com.hunantv.mglive.mqtt.data.MqttResponseData;
import com.hunantv.mglive.ui.adapter.ChatJoinAdapter;
import com.hunantv.mglive.ui.adapter.ChatListAdapter;
import com.hunantv.mglive.ui.adapter.StarLivePagerAdapter;
import com.hunantv.mglive.ui.entertainer.data.ContributionInfoData;
import com.hunantv.mglive.ui.live.StarLiveInputFragment.OnSendContentListener;
import com.hunantv.mglive.ui.live.liveinterface.OnStarLiveCallBack;
import com.hunantv.mglive.ui.live.liveinterface.OnVideoPlayCallBack;
import com.hunantv.mglive.utils.GiftUtil;
import com.hunantv.mglive.utils.GlideRoundTransform;
import com.hunantv.mglive.utils.L;
import com.hunantv.mglive.utils.MessageUtil;
import com.hunantv.mglive.utils.MqttChatUtils;
import com.hunantv.mglive.utils.RoleUtil;
import com.hunantv.mglive.utils.SharePreferenceUtils;
import com.hunantv.mglive.utils.ShareUtil;
import com.hunantv.mglive.utils.StringUtil;
import com.hunantv.mglive.utils.SystemMsgNoticeUtil;
import com.hunantv.mglive.utils.Toast;
import com.hunantv.mglive.widget.GiftShowView;
import com.hunantv.mglive.widget.GiftViewAnim;
import com.hunantv.mglive.widget.LiveMsgView;
import com.hunantv.mglive.widget.PersonValueListDialog;
import com.hunantv.mglive.widget.Toast.ExitLiveDialog;
import com.hunantv.mglive.widget.Toast.LiveStarDialog;
import com.hunantv.mglive.widget.animation.FlakeView;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import tv.danmaku.ijk.media.player.IMediaPlayer;

/**
 * 秀场直播界面（推流、观看）
 * 根据传入的 JUMP_STAR_LIVE_TYPE 参数加载  主播推流Fragment ：StarLiveFragment  或者 用户观看Fragment：StarLiveVideoFragment
 * 聊天输入Fragment ：StarLiveInputFragment
 * 礼物Fragment ：GiftFragment
 * <p/>
 * Created by qiuda on 16/3/24.
 */
public class StarLiveActivity extends BaseActivity implements View.OnClickListener, AdapterView.OnItemClickListener,OnStarLiveCallBack, ChatViewCallback, MqttChatUtils.MqttCallback, MessageUtil.iNotifyMsgListCallBack, ExitLiveDialog.OnClickListener, OnVideoPlayCallBack, StarLiveInputFragment.IinputViewCallBack, OnSendContentListener, View.OnTouchListener {
    public static String JUMP_STAR_LIVE_TYPE = "JUMP_STAR_LIVE_TYPE";// 类型key 主播端true
    public static String JUMP_STAR_LIVE_MODEL = "JUMP_STAR_LIVE_MODEL";//秀场直播对象
    public static String JUMP_STAR_LIVE_CAMERA = "JUMP_STAR_LIVE_CAMERA";// 前置摄像头
    public static String JUMP_STAR_LIVE_PLAY_URL = "JUMP_STAR_LIVE_PLAY_URL";//播放地址
    private static final int MAX_JOIN_SIZE = 10;             //用户进场头像的最大数
    private static final int WHAT_LIVE_COUNT = 0;            //直播计时
    private static final int WHAT_ONLINE_COUNT = 1;          // 在线人数
    private static final int CHAT_NNOTIFY = 2;               //刷新聊天列表
    private static final int CHAT_SEND_MSG = 3;              //喊话
    private static final int CHAT_UPDATE_HOT_VALUE = 4;      //更新人气值
    private static final int CHAT_LAST_MSG = 5;              // 历史消息
    private static final int CHAT_SEND_GIFT = 6;             //送礼
    private static final int CHAT_STAR_LIVE_END = 7;         //关闭直播
    private static final int CHAT_STAR_LIVE_PAUSE = 8;       //直播暂停
    private static final int WHAT_FINISH = 9;                //关闭界面
    private static final int CHAT_STAR_LIVE_RESTART = 10;    // 直播重新开始
    private static final int CHAT_NORMAL_JOIN_IN = 11;       //更新用户进场
    private static final int CHAT_SYSTEM_MSG = 12;            //系统消息
    private boolean mIsLive;                    //是否主播推流
    private boolean mIsStartUpLive = false;               //是否开始推流直播
    private boolean mIsAuthFailure;             //推流地址鉴权失败
    private final int mDelayTime = 1000;        //推流计时间隔

    private int mWidth;                         //屏幕宽度
    private int mHeight;                        //屏幕高度
    private int mCountTime;                     //推流计时变量
    private long mMaxOnLine;                    //高峰观看人数
    private long mHot;                          //开始直播时人气值
    private long mHotCurr;                      //当前直播人气值
    private long mOnLine;                       //当前观看人数
    private long mUpdateTime;                   //入场头像上次更新时间
    private boolean mIsLiveEnd;                 //直播结束的标记
    private boolean mIsScrollBottom;            //滚动到列表底部标记
    private boolean mIsMsgReminderOn;           //显示新消息的标记
    private String mLid;                        //直播间id
    private String mUid;                        //艺人id

    private FrameLayout mFlFragment;
    private FrameLayout mFlLiveMsg;
    private ViewGroup mViewGroup;
    private ViewPager mViewPager;
    private View mHotValueView;
    private View mBottomView;
    private View mViewStarInfo;
    private View mMsgReminder;
    private View mViewBottom;
    private FrameLayout mPagerView;
    private ImageView mIvIcon;
    private ImageView mIvRole;
    private ImageView mIvAttention;
    private TextView mTvName;
    private TextView mTvDes;
    private TextView mTvHotMargin;
    private Button mTvIpunt;
    private TextView mTvSystemMsg;
    private ImageButton mIbtn1;
    private ImageButton mIbtn2;
    private ImageButton mIbtn3;
    private ListView mListViewChat;
    private ImageButton mIbtnGift;
    private TextView mTvHotValue;
    private LinearLayout mLlSystemMsg;
    private RecyclerView mHslChatJoin;

    private List<View> mViews = new ArrayList<>();
    private List<String> mJoinList = new ArrayList<>();

    private PopupWindow mPopupWindowSet;
    private View mPopupWindowPause;
    private View mPopupWindowOffline;
    private View mPopupWindowError;
    private ExitLiveDialog mExitLiveDialog;
    private PersonValueListDialog mPersonValueListDialog;

    private ShareUtil mShareUtil;
    private LiveMsgView mLiveMsgView;
    private GiftShowView mGiftShowView;
    private SystemMsgNoticeUtil mSystemMsgNoticeUtil;
    private MessageUtil mMessageUtil;           //消息刷新频率控制Util
    private GiftViewAnim mGiftViewAnim;
    private GiftFragment mGiftFragment;
    private GiftDataModel mYellGifData;
    private GiftDataModel mShortCutGiftData;
    private ContributionInfoData mContributionInfo;
    private StarLiveVideoFragment mStarLiveVideoFragment;
    private StarLiveInputFragment mStarLiveInputFragment;

    private ChatListAdapter mChatListAdapter;               //聊天列表adapter
    private ChatJoinAdapter mChatJoinAdapter;               //入场头像adapter
    private List<ChatDataModel> mChatList = Collections.synchronizedList(new ArrayList<ChatDataModel>());

    private StarLiveDataModel mStarLiveModel;

    private LiveStarDialog mLiveStarDialog;
    private boolean mIsOpenConnectionMqtt = false;

    private Object obj = new Object();  //显示艺人连线锁

    private Handler mHandler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            super.dispatchMessage(msg);
            switch (msg.what) {
                case WHAT_LIVE_COUNT://直播推流时长统计
                    mCountTime++;
                    int hour = mCountTime / 3600;
                    int minutes = (mCountTime - hour * 3600) / 60;
                    int seconds = mCountTime - hour * 3600 - minutes * 60;
                    DecimalFormat df = new DecimalFormat("00");
                    if (mTvName != null) {//显示 00：00：00
                        mTvName.setText(df.format(hour) + ":" + df.format(minutes) + ":" + df.format(seconds));
                    }
                    mHandler.sendEmptyMessageDelayed(WHAT_LIVE_COUNT, mDelayTime);
                    break;
                case WHAT_ONLINE_COUNT://在线人数显示
                    String onlineStr = (String) msg.obj;
                    if (StringUtil.isNullorEmpty(onlineStr) || "null".equals(onlineStr) || "0".equals(onlineStr)) {
                        mMaxOnLine = 1;
                        mOnLine = 1;
                    } else {
                        try {
                            mOnLine = Long.parseLong(onlineStr);
                            if (mOnLine > mMaxOnLine) {
                                mMaxOnLine = mOnLine;
                            }
                        } catch (NumberFormatException ignored) {
                            mOnLine = 1;
                            if (mOnLine > mMaxOnLine) {
                                mMaxOnLine = mOnLine;
                            }
                        }
                    }
                    mTvDes.setText(getString(R.string.star_live_online, mOnLine));

                    //更新礼物动画等级
                    doGiftAnimLevel(mOnLine);
                    break;
                case CHAT_NNOTIFY://聊天消息刷新聊天列表
                    if (msg.obj != null) {
                        ChatDataModel chatModle = (ChatDataModel) msg.obj;
                        mMessageUtil.addMsg(chatModle);
                    }
                    break;
                case CHAT_SEND_MSG://喊话
                    if (msg.obj != null) {
                        ChatData chatData = (ChatData) msg.obj;
                        mLiveMsgView.displayView(chatData);
                    }
                    break;
                case CHAT_UPDATE_HOT_VALUE://更新人气值
                    if (msg.obj != null) {
                        ChatData chatData = (ChatData) msg.obj;
                        long addHots = 0;

                        if(chatData.getType() == ChatData.CHAT_TYPE_GIFT){
                            if(mYellGifData != null && chatData.getProductId() == mYellGifData.getGid()){
                                //喊话
                                if(chatData.getGrade() <= 0){
                                    addHots = Long.valueOf(mYellGifData.getHots());
                                }
                            }else{
                                addHots = chatData.getHots(mShortCutGiftData) * chatData.getCount();
                            }
                        }else if(chatData.getType() == ChatData.CHAT_TYPE_BUY_GUARD){
                            addHots = Long.valueOf(chatData.getHotValue());
                        }
                        mHotCurr = mHotCurr + addHots;
                        mTvHotValue.setText(mHotCurr + "");
                        mTvHotMargin.setText(mHotCurr + "");
                    }
                    break;
                case CHAT_SEND_GIFT: // 礼物动画
                    if (msg.obj != null) {
                        GiftShowViewDataModel dataModel = (GiftShowViewDataModel) msg.obj;
                        mGiftShowView.show(dataModel);
                    }
                    break;
                case CHAT_LAST_MSG://获取历史消息
                    if (msg.obj != null) {
                        List<ChatDataModel> chatList = (List<ChatDataModel>) msg.obj;
                        mChatList.addAll(chatList);
                        mChatListAdapter.notifyDataSetChanged();
                    }
                    break;
                case CHAT_STAR_LIVE_END:// 直播结束
                    if (msg.obj != null && !isFinishing()) {
                        StarLiveChatModel starLiveChatModel = (StarLiveChatModel) msg.obj;
                        jumpToEnd(starLiveChatModel.getOnline(), starLiveChatModel.getLiveTime(), starLiveChatModel.getHots());
                    }
                    break;
                case CHAT_STAR_LIVE_PAUSE://直播暂停
                    onVideoPuse();
                    break;
                case WHAT_FINISH:
                    finish();
                    break;
                case CHAT_STAR_LIVE_RESTART://直播重新开始
                    if (mPopupWindowPause != null) {
                        mPopupWindowPause.setVisibility(View.GONE);
                    }
                    break;
                case CHAT_NORMAL_JOIN_IN:
                    mChatJoinAdapter.notifyDataSetChanged();

                    break;

                case CHAT_SYSTEM_MSG:
                    if (msg.obj != null) {
                        mSystemMsgNoticeUtil.startDisPlayMsg((ChatData) msg.obj);
                    }
                    break;
            }

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mViewGroup = (ViewGroup) LayoutInflater.from(getContext()).inflate(R.layout.activity_star_live_layout, null);
        setContentView(mViewGroup);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        Intent intent = getIntent();
        mIsLive = intent.getBooleanExtra(JUMP_STAR_LIVE_TYPE, false);
        mLid = intent.getStringExtra(Constant.JUMP_INTENT_LID);
        mUid = intent.getStringExtra(Constant.JUMP_INTENT_UID);
        mStarLiveModel = (StarLiveDataModel) intent.getSerializableExtra(JUMP_STAR_LIVE_MODEL);

        String mPlayUrl = intent.getStringExtra(JUMP_STAR_LIVE_PLAY_URL);
        if (StringUtil.isNullorEmpty(mUid) && mStarLiveModel == null) {
            finish();
            return;
        }
        initView();
        if (mStarLiveModel != null) {
            mLid = mStarLiveModel.getlId();
            mUid = mStarLiveModel.getUid();
            initData();
            setStarView();
        }
        init();
        initStarInfo();
        setGifView();
        setSendMsgView();
        setView();
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager
                .beginTransaction();
        if (mIsLive) {//艺人直播推流端
//            if(mStarLiveFragment == null){
//                mStarLiveFragment = new StarLiveFragment();
//                mStarLiveFragment.startTestUpSpeed();//开始测速
//            }
//            fragmentTransaction.add(R.id.fl_star_live_fragment, mStarLiveFragment);
        } else {//观看端
            mStarLiveVideoFragment = new StarLiveVideoFragment();
            fragmentTransaction.add(R.id.fl_star_live_fragment, mStarLiveVideoFragment);
        }
        fragmentTransaction.commit();

        if (!StringUtil.isNullorEmpty(mLid) && !StringUtil.isNullorEmpty(mPlayUrl)) {
            mStarLiveVideoFragment.setData(mLid, mUid, mPlayUrl);
        }
        mStarLiveVideoFragment.setCallBack(this);
        if (mStarLiveModel != null) {//已经获取到直播间数据，直接设置播放器
            setStarVideo();
        } else {
            getLidByUid(mUid);
        }
        loadChatData();
    }

    /**
     * 初始化变量对象
     */
    private void init() {
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        mWidth = dm.widthPixels;
        mHeight = dm.heightPixels - getStatusBarHeight();
        mGiftViewAnim = new GiftViewAnim(this, mViewGroup);
        mShareUtil = new ShareUtil(this);
        mMessageUtil = new MessageUtil(mChatList, this);
        RelativeLayout mGiftAnimViewGroup = (RelativeLayout) findViewById(R.id.rl_star_live_gift_show_view);
        mGiftShowView = new GiftShowView(this, mGiftAnimViewGroup, true);
        ViewGroup liveMsg = (ViewGroup) findViewById(R.id.fl_star_live_msg);
        mLiveMsgView = new LiveMsgView(this, dm.widthPixels, liveMsg);
        mLiveMsgView.colseAutoBg();
        mExitLiveDialog = new ExitLiveDialog(this, this);
        mPersonValueListDialog = new PersonValueListDialog(this, mUid);
        setViewHW();
        mLiveStarDialog = new LiveStarDialog(getContext(), mStarLiveModel);
        mSystemMsgNoticeUtil = new SystemMsgNoticeUtil(this, mTvSystemMsg, mLlSystemMsg);
    }

    public int getStatusBarHeight() {
        int result = 0;
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    /**
     * 初始化人气值
     */
    private void initData() {
        if (mStarLiveModel == null) {
            return;
        }
        try {
            mHot = Long.parseLong(mStarLiveModel.getHotValue());
            mHotCurr = mHot;
        } catch (NumberFormatException e) {
            L.e(StarLiveActivity.class.getSimpleName(), e);
        }
    }

    /**
     * 初始化界面
     */
    private void initView() {
        mFlFragment = (FrameLayout) findViewById(R.id.fl_star_live_fragment);
        mTvHotMargin = (TextView) findViewById(R.id.tv_star_live_hot_value_margin);
        mTvSystemMsg = (TextView) findViewById(R.id.tv_star_live_system_notice);
        mLlSystemMsg = (LinearLayout) findViewById(R.id.ll_star_live_system_notice);

        mViewPager = (ViewPager) findViewById(R.id.viewpager_star_live_view);
        mIbtn1 = (ImageButton) findViewById(R.id.ibtn_star_live_btn1);
        mIbtn1.setOnClickListener(this);
        mIbtnGift = (ImageButton) findViewById(R.id.ibtn_star_live_gift);
        mIbtnGift.setOnClickListener(this);

        View view = new View(this);
        ViewGroup.LayoutParams ps = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        view.setLayoutParams(ps);
        mViews.add(view);

        mPagerView = (FrameLayout) LayoutInflater.from(this).inflate(R.layout.star_live_view_pager_layout, null);
        mViews.add(mPagerView);

        initPagerView(mPagerView);

        StarLivePagerAdapter adapter = new StarLivePagerAdapter(mViews);
        mViewPager.setAdapter(adapter);
        mViewPager.setCurrentItem(1);           //默认显示第二页
        mViewPager.setOnTouchListener(this);

        SharePreferenceUtils sharePreferenceUtils = new SharePreferenceUtils(this, SharePreferenceUtils.FILE_KEY_HINT_DATA);
        if (sharePreferenceUtils.isStarLiveFirstInit()) {//第一进入显示引导
            View mViewInitView = LayoutInflater.from(this).inflate(R.layout.star_live_fling_init_view, null);
            ImageView iv = (ImageView) mViewInitView.findViewById(R.id.iv_star_live_fling_init);
            AnimationSet animation = new AnimationSet(true);
            animation.setDuration(1500);
            animation.setInterpolator(new AccelerateDecelerateInterpolator());

            TranslateAnimation translateAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 5, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0);
            translateAnimation.setDuration(1500);
            translateAnimation.setRepeatMode(Animation.RESTART);
            translateAnimation.setRepeatCount(Animation.INFINITE);
            animation.addAnimation(translateAnimation);

            AlphaAnimation alphaAnimation = new AlphaAnimation(1, 0);
            alphaAnimation.setDuration(1500);
            alphaAnimation.setRepeatMode(Animation.RESTART);
            alphaAnimation.setRepeatCount(Animation.INFINITE);
            animation.addAnimation(alphaAnimation);

            iv.startAnimation(animation);
            mViewInitView.setVisibility(View.VISIBLE);
            mViewInitView.setOnClickListener(this);
            mViewGroup.addView(mViewInitView);
        }

        mFlLiveMsg = (FrameLayout) findViewById(R.id.framlayout_star_live_msg);
    }

    /**
     * 初始化ViewPager 的第二页（第一页为空白页，第二页为显示主页，此方法设置第二页）
     *
     * @param view
     */
    private void initPagerView(View view) {
        mHslChatJoin = (RecyclerView) view.findViewById(R.id.hls_list_view_input_audience);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mHslChatJoin.setLayoutManager(linearLayoutManager);
        mChatJoinAdapter = new ChatJoinAdapter(StarLiveActivity.this, mJoinList);
        mHslChatJoin.setAdapter(mChatJoinAdapter);


        mIvIcon = (ImageView) view.findViewById(R.id.iv_star_live_title_icon);
        mIvRole = (ImageView) view.findViewById(R.id.iv_star_live_title_role);
        mIvAttention = (ImageView) view.findViewById(R.id.iv_star_live_title_attention);
        mIvAttention.setOnClickListener(this);
        mViewStarInfo = view.findViewById(R.id.ll_star_live_star_info);
        mViewStarInfo.setOnClickListener(this);
        mTvName = (TextView) view.findViewById(R.id.tv_star_live_title_name);
        mTvDes = (TextView) view.findViewById(R.id.tv_star_live_title_online);

        mIbtn2 = (ImageButton) view.findViewById(R.id.ibtn_star_live_btn2);
        mIbtn2.setOnClickListener(this);
        mIbtn3 = (ImageButton) view.findViewById(R.id.ibtn_star_live_btn3);
        mIbtn3.setOnClickListener(this);
        mListViewChat = (ListView) view.findViewById(R.id.lv_star_live_chat_list);
        mListViewChat.setOnItemClickListener(this);
        mBottomView = view.findViewById(R.id.rl_star_live_bottom_view);

        mTvIpunt = (Button) view.findViewById(R.id.tv_star_live_edit_input);
        mTvIpunt.setOnClickListener(this);
        mViewBottom = view.findViewById(R.id.ll_star_live_bottom_view);

        mTvHotValue = (TextView) view.findViewById(R.id.tv_star_live_hot_value);
        mHotValueView = view.findViewById(R.id.ll_star_live_hot_value_view);
        mHotValueView.setOnClickListener(this);

        mChatListAdapter = new ChatListAdapter(mChatList, this, true);
        mListViewChat.setAdapter(mChatListAdapter);

        mMsgReminder = view.findViewById(R.id.ll_star_live_chat_remider_view);
        mMsgReminder.setVisibility(View.GONE);
        mMsgReminder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                v.setVisibility(View.GONE);
                if (null != mListViewChat) {
                    mListViewChat.setSelection(mListViewChat.getBottom());
                }
            }
        });
        mListViewChat.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                //判断是否滑动到最底部
                mIsScrollBottom = view.getLastVisiblePosition() == (totalItemCount - 1);
                if (mIsScrollBottom && mMsgReminder.getVisibility() == View.VISIBLE) {
                    mMsgReminder.setVisibility(View.GONE);
                }
            }
        });

    }

    /**
     * 更新礼物动画等级
     */
    private void doGiftAnimLevel(long onlineNum) {
        int level = FlakeView.LEVEL_NUM_1;
        if (onlineNum <= 100) {
            level = FlakeView.LEVEL_NUM_1;
        } else if (onlineNum > 100 && onlineNum <= 500) {
            level = FlakeView.LEVEL_NUM_2;
        } else if (onlineNum > 500 && onlineNum <= 2000) {
            level = FlakeView.LEVEL_NUM_3;
        } else if (onlineNum > 2000 && onlineNum <= 10000) {
            level = FlakeView.LEVEL_NUM_4;
        } else if (onlineNum > 10000) {
            level = FlakeView.LEVEL_NUM_5;
        }

        if (mFlakeView != null) {
            if (level != mFlakeView.getLevel()) {
                mFlakeView.setLevel(level);
            }
        }
    }

    /**
     * 开启礼物动画
     */
    private FlakeView mFlakeView;

    private void doGiftAnim(final ViewGroup rootView) {

        int x = mIbtnGift.getLeft() + mIbtnGift.getWidth() / 2;
        int y = mIbtnGift.getTop();
        if (x > 0 && y > 0) {//外部已经布局完成
            if (mFlakeView == null) {
                mFlakeView = new FlakeView(getContext());
                mFlakeView.setStartPosition(x, y);
                rootView.addView(mFlakeView);
                mFlakeView.start();
            }
        } else {//外部还没布局完成
            mIbtnGift.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    if (Build.VERSION.SDK_INT > 15) {
                        mIbtnGift.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                    }
                    if (mFlakeView == null) {
                        mFlakeView = new FlakeView(getContext());
                        int x = mIbtnGift.getLeft() + mIbtnGift.getWidth() / 2;
                        int y = mIbtnGift.getTop();
                        mFlakeView.setStartPosition(x, y);
                        rootView.addView(mFlakeView);
                        mFlakeView.start();
                    }
                }
            });
        }
    }

    private void setViewHW() {
        FrameLayout.LayoutParams ps = (FrameLayout.LayoutParams) mBottomView.getLayoutParams();
        ps.height = mHeight;

        View view = findViewById(R.id.fl_star_live_fragment);
        FrameLayout.LayoutParams psFragment = (FrameLayout.LayoutParams) view.getLayoutParams();
        psFragment.height = mHeight;

        FrameLayout.LayoutParams psMsg = (FrameLayout.LayoutParams) mFlLiveMsg.getLayoutParams();
        psMsg.height = mHeight;
        mFlLiveMsg.setLayoutParams(psMsg);
    }

    private void switchReminder() {
        mMsgReminder.setVisibility(mIsMsgReminderOn && !mIsScrollBottom ? View.VISIBLE : View.GONE);
    }

    /**
     * 设置界面Button
     */
    private void setView() {
        if (mIsLive) {//直播推流端显示：美颜、更多设置
            mIbtn2.setImageResource(R.drawable.star_live_beauty_bg);
            mIbtn2.setSelected(true);
            mIbtn3.setImageResource(R.drawable.star_live_more);
            mIbtn3.setVisibility(View.VISIBLE);
            mIvAttention.setVisibility(View.GONE);
        } else {//观看端显示：粉TA、分享
            mIvAttention.setVisibility(View.VISIBLE);
            mIbtn2.setImageResource(R.drawable.star_live_share_new);
        }
    }

    /**
     * 设置显示的界面
     */
    private void setStarView() {
        Glide.with(this).load(mStarLiveModel.getPhoto()).error(R.drawable.default_icon).placeholder(R.drawable.default_icon).transform(new GlideRoundTransform(this, R.dimen.height_35dp)).into(mIvIcon);
        mTvHotValue.setText(mHotCurr + "");
        mTvHotMargin.setText(mHotCurr + "");
        Glide.with(this).load(RoleUtil.getRoleIcon(mStarLiveModel.getRole())).into(mIvRole);
        Message msg = mHandler.obtainMessage(WHAT_ONLINE_COUNT, mStarLiveModel.getCount());
        mHandler.sendMessage(msg);
        ImageView cameraImage = (ImageView) mPagerView.findViewById(R.id.iv_star_live_title_camera_tag);
        if (mIsLive) {
            mTvName.setText("00:00:00");
            startCameraTagAinm(cameraImage);
            dispalyView(mIbtn3);
        } else {
            cameraImage.setVisibility(View.GONE);
            mTvName.setText(mStarLiveModel.getNickName());
            getIsFollowStatus(mStarLiveModel.getUid());
        }
        dispalyView(mIbtn2);
        dispalyView(mViewStarInfo);
        if (!"0".equals(mStarLiveModel.getShowHotValue())) {
            dispalyView(mHotValueView);
        }
        if ("1".equals(mStarLiveModel.getGiftInvalid())) {
            mIbtnGift.setVisibility(View.GONE);
        } else {
            doGiftAnim(mPagerView);
        }
        dispalyView(mBottomView);
    }

    /**
     * 主播推流断，推流计时的红点动画
     *
     * @param imageView
     */
    private void startCameraTagAinm(final ImageView imageView) {
        imageView.setVisibility(View.VISIBLE);
        final AlphaAnimation alphaAnimationhide = new AlphaAnimation(1f, 0.1f);
        alphaAnimationhide.setDuration(1000);

        final AlphaAnimation alphaAnimationShow = new AlphaAnimation(0.1f, 1);
        alphaAnimationShow.setDuration(500);

        alphaAnimationhide.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                imageView.clearAnimation();
                imageView.startAnimation(alphaAnimationShow);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

        alphaAnimationShow.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                imageView.clearAnimation();
                imageView.startAnimation(alphaAnimationhide);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        imageView.startAnimation(alphaAnimationhide);
    }


    /**
     * view渐入的的动画方法
     *
     * @param view 需要渐入的view
     */
    private void dispalyView(final View view) {
        if (view == null) {
            return;
        }
        AlphaAnimation alphaAnim = new AlphaAnimation(0, 1);
        alphaAnim.setDuration(500);
        alphaAnim.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                view.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        view.startAnimation(alphaAnim);
    }

    /**
     * 设置礼物Fragment
     */
    public void setGifView() {
        mGiftFragment = (GiftFragment) getSupportFragmentManager().findFragmentById(R.id.fragmenrt_star_live_gift);
        mGiftFragment.setGiftAnimListener(this);
        if (mStarLiveModel != null && mIsLive) {
            mGiftFragment.setStarInfo(mStarLiveModel.getStarModel());
        }
    }

    /**
     * 设置发送消息Fragment
     */
    public void setSendMsgView() {
        mStarLiveInputFragment = (StarLiveInputFragment) getSupportFragmentManager().findFragmentById(R.id.fragmenrt_star_live_send_msg);
        mStarLiveInputFragment.setInputCallBack(this);
        mStarLiveInputFragment.setContentListener(this);
    }

    /**
     * 主播端显示更多设置
     *
     * @param view 点击的button
     */
    private void showPopupWindow(View view) {
        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(this).inflate(
                R.layout.star_live_more_set_popupwindow, null);
        // 设置按钮的点击事件
        View cameraView = contentView.findViewById(R.id.ll_star_live_more_set_camera);
        cameraView.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (mPopupWindowSet != null) {
                    mPopupWindowSet.dismiss();
                    mPopupWindowSet = null;
                }
            }
        });

        View flashlightView = contentView.findViewById(R.id.ll_star_live_more_set_flashlight);
        flashlightView.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Toast.makeText(StarLiveActivity.this, getString(R.string.star_live_flashlight_error), Toast.LENGTH_SHORT).show();
                if (mPopupWindowSet != null) {
                    mPopupWindowSet.dismiss();
                    mPopupWindowSet = null;
                }
            }
        });

        View shareView = contentView.findViewById(R.id.ll_star_live_more_set_share);
        shareView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mShareUtil != null) {
                    mShareUtil.share(getUid(), getToken(), ShareUtil.TYPE_LIVE_PHONE, mStarLiveModel.getlId(), mStarLiveModel.getUid(), "", "");
                }
                if (mPopupWindowSet != null) {
                    mPopupWindowSet.dismiss();
                    mPopupWindowSet = null;
                }
            }
        });

        mPopupWindowSet = new PopupWindow(contentView,
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);

        mPopupWindowSet.setTouchable(true);
        mPopupWindowSet.setBackgroundDrawable(getResources().getDrawable(
                R.color.transparent));
        contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int popupWidth = contentView.getMeasuredWidth();
        int popupHeight = contentView.getMeasuredHeight();
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        if (!Util.isOnMainThread() || isFinishing()) {
            return;
        }
        mPopupWindowSet.showAtLocation(view, Gravity.NO_GRAVITY, location[0] - popupWidth / 2,
                location[1] - popupHeight);
    }

    /**
     * 显示艺人连线中的view
     */
    private void showPausePopupwindow() {
        if (mPopupWindowPause == null) {
            mPopupWindowPause = findViewById(R.id.v_star_live_pause);
        }
        ImageView iv = (ImageView) mPopupWindowPause.findViewById(R.id.iv_star_live_pause_anim);
        AnimationDrawable animationDrawable = (AnimationDrawable) iv.getDrawable();
        animationDrawable.start();
        mPopupWindowPause.setVisibility(View.VISIBLE);
    }

    /**
     * 显示艺人不在线的view
     */
    private void showOfflinePopupwindow() {
        if (mPopupWindowOffline == null) {
            mPopupWindowOffline = findViewById(R.id.v_star_live_offline);
            ImageView ivIcon = (ImageView) mPopupWindowOffline.findViewById(R.id.iv_star_live_offline_icon);
            if (Util.isOnMainThread() && !isFinishing()) {
                Glide.with(this).load(mStarLiveModel.getPhoto()).transform(new GlideRoundTransform(this, R.dimen.height_40dp)).into(ivIcon);
            }
            Button btnGo = (Button) mPopupWindowOffline.findViewById(R.id.btn_star_live_offline_go_starinfo);
            btnGo.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(StarLiveActivity.this, StarDetailActivity.class);
                    intent.putExtra(StarDetailActivity.KEY_STAR_ID, mStarLiveModel.getUid());
                    startActivity(intent);
                    finish();
                }
            });
        }
        mPopupWindowOffline.setVisibility(View.VISIBLE);
    }

    /**
     * 显示艺人推流异常的veiw
     */
    private void showLiveErrorPopupwindow() {
        if (mPopupWindowError == null) {
            mPopupWindowError = findViewById(R.id.v_star_live_error);
        }
        ImageView iv = (ImageView) mPopupWindowError.findViewById(R.id.iv_star_live_error_notice);
        AnimationDrawable animationDrawable = (AnimationDrawable) iv.getDrawable();
        animationDrawable.start();
        mPopupWindowError.setVisibility(View.VISIBLE);
    }

    /**
     * 更新用户进场头像
     *
     * @param uid    用户id
     * @param avatar 用户头像
     */
    private synchronized void updateJoin(String uid, String avatar) {
        L.d(TAG, "updateJoin");
        long time = System.currentTimeMillis();
        String mLoginUid = getUid();
        //800ms 更新一次进场头像，并且不过滤当前观看用户的进场头像
        if (time - mUpdateTime < 800 && (StringUtil.isNullorEmpty(uid) || !uid.equals(mLoginUid))) {
            return;
        }
        mUpdateTime = time;
        L.d(TAG, "updateJoin_update");
        if (mJoinList.size() > MAX_JOIN_SIZE) {
            mJoinList.remove(mJoinList.size() - 1);
        }
        //先删除该用户历史头像，再添加新的进去
        mJoinList.remove(avatar);
        mJoinList.add(0, avatar);
        mHandler.sendEmptyMessage(CHAT_NORMAL_JOIN_IN);
    }

    /**
     * 跳转直播结束界面
     *
     * @param count
     * @param duration
     * @param hot
     */
    private void jumpToEnd(String count, String duration, String hot) {
        if (mStarLiveModel != null) {
            Intent intent = new Intent(this, StarLiveEndActivity.class);
            intent.putExtra(StarLiveEndActivity.JUMP_STAR_LIVE_TPYE, false);
            intent.putExtra(StarLiveEndActivity.JUMP_STAR_LIVE_END_ROLE, mStarLiveModel.getRole());
            intent.putExtra(StarLiveEndActivity.JUMP_STAR_LIVE_END_ID, mStarLiveModel.getUid());
            intent.putExtra(StarLiveEndActivity.JUMP_STAR_LIVE_END_NAME, mStarLiveModel.getNickName());
            intent.putExtra(StarLiveEndActivity.JUMP_STAR_LIVE_END_ICON, mStarLiveModel.getPhoto());
            intent.putExtra(StarLiveEndActivity.JUMP_STAR_LIVE_END_DURATION, duration);
            intent.putExtra(StarLiveEndActivity.JUMP_STAR_LIVE_END_COUNT, count);
            intent.putExtra(StarLiveEndActivity.JUMP_STAR_LIVE_END_HOT, hot);
            startActivity(intent);
        } else {
            Toast.makeText(this, getString(R.string.star_live_end), Toast.LENGTH_SHORT).show();
        }
        finish();
    }

    /**
     * 关闭界面
     */
    private void onFinish() {
            finish();
    }

    /**
     * 获取用户信息
     */
    private void initStarInfo() {
        Map<String, String> body = new FormEncodingBuilderEx()
                .add("uid", mUid)
                .build();
        post(BuildConfig.URL_STAR_INFO, body);
    }

    /**
     * 粉TA
     *
     * @param starId 艺人id
     */
    private void followStar(String starId) {
        Map<String, String> body = new FormEncodingBuilderEx()
                .add("uid", getUid())
                .add("followid", starId)
                .build();
        post(BuildConfig.URL_ADD_FOLLOW, body);
    }

    /**
     * 获取直播间数据
     *
     * @param starId 艺人id
     */
    private void getLidByUid(String starId) {
        Map<String, String> body = new FormEncodingBuilderEx()
                .add("uid", getUid())
                .add("auid", starId)
                .build();
        post(BuildConfig.URL_GET_LIVE_INFO_BY_UID, body);
    }


    /**
     * 获取最新的20条聊天记录
     */
    public void getLastMsg() {
        FormEncodingBuilderEx build = new FormEncodingBuilderEx()
                .add("uid", getUid())
                .add("flag", getMqttFlag())
                .add("key", getMqttKey())
                .add("artistIds", mUid);

        if (isLogin()) {
            UserInfoData data = getUserInfo();
            if (data != null) {
                build.add("img", data.getPhoto());
            }
        }
        if (mContributionInfo != null) {
            if (!StringUtil.isNullorEmpty(mContributionInfo.getGradeLevel())) {
                build.add("grade", mContributionInfo.getGradeLevel());
            } else {
                build.add("grade", "0");
            }
        } else {
            if (isLogin()) {
                build.add("grade", "1");
            } else {
                build.add("grade", "0");
            }
        }
        Map<String, String> body = build.build();
        post(BuildConfig.CHAT_GET_LAST_MSG_PATH, body);
    }


    /**
     * 查询守护信息
     */
    private void loadContrInfo() {
        if (isLogin() && mStarLiveModel != null) {
            Map<String, String> body = new FormEncodingBuilderEx()
                    .add("uid", getUid())
                    .add("aid", mStarLiveModel.getUid())
                    .build();
            post(BuildConfig.GET_CONTRIBUTION_INFO, body);
            L.d(TAG + "守护信息UID：", getUid());
            L.d(TAG + "守护信息STARID：", mStarLiveModel.getUid());
        } else {
            getLastMsg();
        }
    }


    /**
     * 获取用户消息数据
     */
    private void loadUserMessage() {
        //获取用户消息数据
        Map<String, String> param = new FormEncodingBuilderEx()
                .add("uid", getUid())
                .build();
        post(BuildConfig.URL_MESSAGE_MYNOTICE, param);
    }

    /**
     * 更新直播状态
     */
    public void liveStatusNotify(String type) {
        //没有推流端
//        Map<String, String> param = new FormEncodingBuilderEx()
//                .add("uid", getUid())
//                .add("online", mMaxOnLine + "")
//                .add("hots", "" + (mHotCurr - mHot))
//                .add("liveTime", mTvName.getText().toString())
//                .add("type", type)
//                .add("clientId", getMqttClientId())
//                .add("key", getMqttKey())
//                .add("flag", getMqttFlag())
//                .build();
//        post(BuildConfig.URL_LIVE_STATUS_NOTIFY, param);
    }

    /**
     * 获取聊天数据
     */
    private void loadChatData() {
        if (GiftUtil.getInstance().getShout() == null) {
            post(BuildConfig.GET_SHOUT_GIFT, new FormEncodingBuilderEx().build());
        } else {
            loadShout();
        }
    }


    /**
     * 获取礼物数据
     */
    private void loadGiftData() {
        if (GiftUtil.getInstance().getShortcutGift() == null) {
            post(BuildConfig.GET_SHORTCUT_GIFT, new FormEncodingBuilderEx().build());
        } else {
            mShortCutGiftData = GiftUtil.getInstance().getShortcutGift();
        }
    }

    /**
     * 发送守护进场的消息
     */
    public void sendGuardMessage() {
        if (!isLogin() || StringUtil.isNullorEmpty(getMqttClientId()) || mStarLiveModel == null) {
            return;
        }
        FormEncodingBuilderEx builder = new FormEncodingBuilderEx();
        builder.add("uid", getUid());
        builder.add("artistIds", mStarLiveModel.getUid());
        builder.add("token", getToken());
        builder.add("tip", "");
        builder.add("clientId", getMqttClientId());
        builder.add("flag", getMqttFlag());
        builder.add("key", getMqttKey());
        post(BuildConfig.SEND_GUARD_MSG, builder.build());
    }

    /**
     * 获取粉TA的状态
     *
     * @param starId 艺人id
     */
    private void getIsFollowStatus(String starId) {
        if (isLogin()) {
            Map<String, String> param = new FormEncodingBuilderEx()
                    .add("uid", MaxApplication.getInstance().getUid())
                    .add("token", MaxApplication.getInstance().getToken())
                    .add("artistId", starId != null ? starId : "").build();
            post(BuildConfig.URL_GET_IS_FOLLOWED, param);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        resume();
        if (mFlakeView != null) {
            mFlakeView.resume();
        }

        if(mIsOpenConnectionMqtt){
            connectionMqtt();
        }
    }

    private void connectionMqtt(){
        //重新连接mqtt
        if((!getMqtt().isConnection() && mStarLiveModel != null)
                || (mStarLiveModel != null && !StringUtil.isNullorEmpty(mStarLiveModel.getFlag()) && !StringUtil.isNullorEmpty(mStarLiveModel.getKey())
                && !mStarLiveModel.getFlag().equals(getMqtt().getFlag()) && !mStarLiveModel.getKey().equals(getMqtt().getFlag()))){
            if (StringUtil.isNullorEmpty(mStarLiveModel.getFlag())) {
                mStarLiveModel.setFlag("liveshow");
                mStarLiveModel.setKey(mStarLiveModel.getUid());
            }
            getMqtt().startMqttService(mStarLiveModel.getFlag(), mStarLiveModel.getKey(), this);
        }
    }

    /**
     * resume 更新礼物列表
     * 推流端：继续开始计时
     * 观看段：隐藏暂停view的显示
     */
    private void resume() {
        loadGiftData();
        if (mIsLive && mIsStartUpLive) {
            mHandler.sendEmptyMessageDelayed(WHAT_LIVE_COUNT, mDelayTime);
        } else {
            if (mPopupWindowPause != null) {
                mPopupWindowPause.setVisibility(View.GONE);
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        pause();
        if (mFlakeView != null) {
            mFlakeView.pause();
        }
        mIsOpenConnectionMqtt = true;
    }

    /**
     * 推流端发送推流暂停的推送消息，暂停推流计时
     */
    private void pause() {
        if (mIsLive) {
            if (!StringUtil.isNullorEmpty(getMqttClientId()) && !mIsLiveEnd) {
                liveStatusNotify("8");//直播暂停
            }
            mHandler.removeMessages(WHAT_LIVE_COUNT);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Glide.get(this).clearMemory();
        if (mFlakeView != null) {
            mFlakeView.onDestory();
        }
    }

    @Override
    public Object asyncExecute(String url, ResultModel resultModel) {
        if (BuildConfig.URL_GET_LIVE_INFO_BY_UID.equals(url)) {
            return JSON.parseObject(resultModel.getData(), StarLiveDataModel.class);
        } else if (BuildConfig.GET_CONTRIBUTION_INFO.equals(url)) {
            return JSON.parseObject(resultModel.getData(), ContributionInfoData.class);
        } else if (url.contains(BuildConfig.CHAT_GET_LAST_MSG_PATH)) {
            return doLastMsg(resultModel);
        } else if (url.contains(BuildConfig.GET_SHOUT_GIFT) || url.contains(BuildConfig.GET_SHORTCUT_GIFT)) {
            return JSON.parseObject(resultModel.getData(), GiftDataModel.class);
        } else if (BuildConfig.URL_MESSAGE_MYNOTICE.equals(url)) {
            return JSON.parseObject(resultModel.getData(), NoticeMessage.class);
        }
        return super.asyncExecute(url, resultModel);
    }

    @NonNull
    public Object doLastMsg(ResultModel resultModel) {
        MqttLastMsgData data = JSON.parseObject(resultModel.getData(), MqttLastMsgData.class);
        Message msg = mHandler.obtainMessage(WHAT_ONLINE_COUNT, data.getOnline());
        mHandler.sendMessage(msg);
        List<String> images = data.getImgList();
        if (images != null) {
            for (int i = 0; i < MAX_JOIN_SIZE && i < images.size(); i++) {
                mJoinList.add(images.get(i));
            }
            mHandler.sendEmptyMessage(CHAT_NORMAL_JOIN_IN);
        }

        List<ChatDataModel> chatList = new ArrayList<>();
        if (null != data.getLastMsg() && data.getLastMsg().size() > 0) {
            for (int i = 0; i < data.getLastMsg().size(); i++) {
                ChatData da = JSON.parseObject(data.getLastMsg().get(i), ChatData.class);
                if (null != da) {
                    ChatDataModel chatModle = da.toChatModle();
                    chatList.add(chatModle);
                }
            }
        }
        return chatList;
    }

//    @Override
//    public boolean showWindow(GiftingInfoModel model) {
//        return super.showWindow(model);
//    }

    @Override
    public void onSucceed(String url, ResultModel resultModel) throws JSONException {
        super.onSucceed(url, resultModel);
        if (BuildConfig.URL_REMOVE_FOLLOW.contains(url)) {
            mIvAttention.setSelected(true);
        } else if (BuildConfig.URL_ADD_FOLLOW.contains(url)) {
            mIvAttention.setVisibility(View.GONE);
            mIvAttention.setSelected(false);
            Toast.makeText(getContext(), "已粉TA", Toast.LENGTH_SHORT).show();
        } else if (BuildConfig.URL_GET_LIVE_INFO_BY_UID.equals(url)) {
            mStarLiveModel = (StarLiveDataModel) resultModel.getDataModel();
            mLid = mStarLiveModel.getlId();
            initData();
            setStarView();
            setStarVideo();
            mStarLiveVideoFragment.setData(mLid, mUid);
        } else if (BuildConfig.GET_SHORTCUT_GIFT.equals(url)) {
            GiftUtil.getInstance().setShortcutGift((GiftDataModel) resultModel.getDataModel());
            mShortCutGiftData = GiftUtil.getInstance().getShortcutGift();
        } else if (BuildConfig.GET_SHOUT_GIFT.equals(url)) {
            GiftUtil.getInstance().setShout((GiftDataModel) resultModel.getDataModel());
            loadShout();
        } else if (BuildConfig.GET_CONTRIBUTION_INFO.equals(url)) {
            //守护信息
            mContributionInfo = (ContributionInfoData) resultModel.getDataModel();
            if (mStarLiveInputFragment != null) {
                mStarLiveInputFragment.setContributionInfoData(mContributionInfo);
            }
            getLastMsg();
        } else if (BuildConfig.CHAT_GET_LAST_MSG_PATH.equals(url)) {
            List<ChatDataModel> chatList = (List<ChatDataModel>) resultModel.getDataModel();
            Message msg = mHandler.obtainMessage(CHAT_LAST_MSG, chatList);
            mHandler.sendMessage(msg);
        } else if (BuildConfig.URL_MESSAGE_MYNOTICE.equals(url)) {
            NoticeMessage noticeMessage = (NoticeMessage) resultModel.getDataModel();
            mStarLiveModel.setDynamicCount(noticeMessage.getDyCount() + "");
            mStarLiveModel.setFollowCount(noticeMessage.getFollowCount() + "");
            mStarLiveModel.setFansCount(noticeMessage.getFansCount() + "");
        }else if (BuildConfig.URL_GET_IS_FOLLOWED.equals(url)) {
            try {
                JSONObject jsonData = new JSONObject(resultModel.getData());
                boolean isFollow = jsonData.getBoolean("isFollowed");
                if (isFollow) {
                    mIvAttention.setVisibility(View.GONE);
                }
            } catch (Exception e) {

            }
        }

    }

    /**
     * 设置观看端、连接聊天室
     */
    private void setStarVideo() {
        mPersonValueListDialog.setuName(mStarLiveModel.getNickName());
        if (mStarLiveModel != null) {
            mLiveStarDialog.setStar(mStarLiveModel);
            mStarLiveInputFragment.setStarInfo(mStarLiveModel.getUid(), mStarLiveModel.getNickName());
            if (StringUtil.isNullorEmpty(mStarLiveModel.getFlag())) {
                mStarLiveModel.setFlag("mgtv_live");
                mStarLiveModel.setKey("liveshow_"+mStarLiveModel.getUid());
            }
            getMqtt().startMqttService(mStarLiveModel.getFlag(), mStarLiveModel.getKey(), this);
            if (mGiftFragment != null) {
                mGiftFragment.setStarInfo(mStarLiveModel.getStarModel());
            }
            if (!StringUtil.isNullorEmpty(mLid) && mStarLiveVideoFragment != null) {
                if (!"online".equals(mStarLiveModel.getLiveStatus())) {
                    mStarLiveVideoFragment.hideAnimView();
                    showOfflinePopupwindow();
                }
            }
        }
        loadContrInfo();
    }

    private void loadShout() {
        mYellGifData = GiftUtil.getInstance().getShout();
        if (mStarLiveInputFragment != null) {
            mStarLiveInputFragment.setGiftData(mYellGifData);
        }
    }

    @Override
    public void onFailure(String url, ResultModel resultModel) {
        super.onFailure(url, resultModel);
        if (BuildConfig.GET_CONTRIBUTION_INFO.equals(url)) {
            getLastMsg();
        }else if (BuildConfig.URL_GET_LIVE_INFO_BY_UID.equals(url)) {//获取艺人信息失败

            final String failStr = resultModel.getMsg();
            mViewGroup.postDelayed(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(StarLiveActivity.this,failStr, Toast.LENGTH_SHORT).show();
                    finish();//退出当前直播页
                }
            }, 1500);

        }else {
            Toast.makeText(this, resultModel.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.tv_star_live_edit_input) {
            if (StringUtil.isNullorEmpty(getMqttClientId())) {
                return;
            }
            mIbtnGift.setVisibility(View.INVISIBLE);
            mViewBottom.setVisibility(View.INVISIBLE);
            mStarLiveInputFragment.showInputView("");

        } else if (i == R.id.ibtn_star_live_btn1) {
            if (mIsLive && mExitLiveDialog != null) {
                mExitLiveDialog.show(mOnLine + "");
            } else {
                onFinish();
            }

        } else if (i == R.id.ibtn_star_live_btn2) {
            if (mIsLive) {
            } else {
                if (mStarLiveModel != null) {
                    mShareUtil.share(getUid(), getToken(), ShareUtil.TYPE_LIVE_PHONE, mStarLiveModel.getlId(), mStarLiveModel.getUid(), "", "");
                }
            }

        } else if (i == R.id.ibtn_star_live_btn3) {
            showPopupWindow(v);

        } else if (i == R.id.ibtn_star_live_gift) {
            if (!isLogin()) {
                jumpToLogin("登录以后才可以送礼哦~");
                return;
            }
            if (mGiftFragment != null) {
                mGiftFragment.showGiftView();
            }

        } else if (i == R.id.iv_star_live_title_attention) {
            if (mStarLiveModel == null) {
                return;
            }
            if (!isLogin()) {
                jumpToLogin("登录以后才可以粉TA哦~");
                return;
            }
            if (!v.isSelected()) {
                followStar(mStarLiveModel.getUid());
            }

        } else if (i == R.id.ll_star_live_hot_value_view) {
            if (mPersonValueListDialog != null) {
                mPersonValueListDialog.show();
            }

        } else if (i == R.id.ll_star_live_star_info) {
            if (mLiveStarDialog != null && !mLiveStarDialog.isShowing()) {
                mLiveStarDialog.show();
            }

        } else if (i == R.id.v_star_live_fling_init_view) {
            v.setVisibility(View.GONE);
            mViewGroup.removeView(v);

        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            if (mGiftFragment != null && mGiftFragment.onBackpressed()) {
                return true;
            }
            if (mStarLiveInputFragment != null && mStarLiveInputFragment.onBackpressed()) {
                return true;
            }
            if (mIsLive && mExitLiveDialog != null) {
                mExitLiveDialog.show(mOnLine + "");
            } else {
                onFinish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (StringUtil.isNullorEmpty(getMqttClientId())) {
            return;
        }
        mIbtnGift.setVisibility(View.INVISIBLE);
        mViewBottom.setVisibility(View.INVISIBLE);
        ChatDataModel data = (ChatDataModel) parent.getAdapter().getItem(position);
        mStarLiveInputFragment.showInputView("@" + data.name1 + " ");
    }

    @Override
    public void startAnim(String image, String text, int fromx, int fromy) {
        mGiftViewAnim.startGiftViewAnim(image, text, fromx, mWidth / 2, fromy, mHeight / 3);
    }

    @Override
    public void hasMsg(ChatData chatData) {

    }

    @Override
    public void changeOnline(String changeStr) {

    }

    @Override
    public void changeGiftView(boolean isDisplay) {

    }

    @Override
    public void changeStarHotValue(long hotValue) {

    }

    @Override
    public void arrivedMessage(MqttResponseData data) {
        try {
            ChatData chatData = JSON.parseObject(data.getDatas(), ChatData.class);
            if (chatData != null) {
                if (chatData.getType() != 0) {
                    Message msg = mHandler.obtainMessage(WHAT_ONLINE_COUNT, "" + data.getOnline());
                    mHandler.sendMessage(msg);
                }
                showChatData(chatData, data);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 显示聊天内容
     *
     * @param chatData mSendChatData
     */
    private void showChatData(ChatData chatData, MqttResponseData data) {
        ChatDataModel chatModle;
        if (chatData.getType() == ChatData.CHAT_TYPE_GIFT) {
            if (mStarLiveModel == null) {
                return;
            }
            if (mYellGifData != null && mYellGifData.getGid() == chatData.getProductId()) {//喊话
                Message msg = mHandler.obtainMessage(CHAT_SEND_MSG, chatData);
                mHandler.sendMessage(msg);
            } else {
                GiftShowViewDataModel dataModel = chatData.getGiftShowDataModel(mStarLiveModel.getStarModel());
                if (dataModel == null) {
                    dataModel = chatData.getGiftShowDataModel(mShortCutGiftData, mStarLiveModel.getStarModel());
                }
                Message msg = mHandler.obtainMessage(CHAT_SEND_GIFT, dataModel);//礼物
                mHandler.sendMessage(msg);
                chatModle = chatData.toChatModle(mShortCutGiftData, mStarLiveModel.getNickName());
                if(!StringUtil.isNullorEmpty(chatModle.giftName) && !StringUtil.isNullorEmpty(chatModle.giftPhoto))
                {
                    //只有匹配到礼物才显示
                    sendMsg(chatModle);
                }
            }
            //刷新人气值
            Message msg = mHandler.obtainMessage(CHAT_UPDATE_HOT_VALUE, chatData);
            mHandler.sendMessage(msg);
        } else if (ChatData.CHAT_TYPE_VIP_JOIN_IN == chatData.getType()) {
            if (chatData.getGrade() >= 1) {
                chatModle = chatData.toChatModle();
                sendMsg(chatModle);
            }
        } else if (ChatData.CHAT_TYPE_CONTENT == chatData.getType() || ChatData.CHAT_TYPE_DANMO == chatData.getType()) {
            chatModle = chatData.toChatModle();
            if (!isLogin() || !getUid().equals(chatData.getUuid())) {
                sendMsg(chatModle);
            }
        } else if (ChatData.CHAT_TYPE_STAR_CHANGE == chatData.getType()) {
//            Message msg = mHandler.obtainMessage(CHAT_SEND_MSG, chatData);
//            mHandler.sendMessage(msg);
        } else if (ChatData.CHAT_TYPE_LIVE_END == chatData.getType()) {
            StarLiveChatModel starLiveChatModel = JSON.parseObject(data.getDatas(), StarLiveChatModel.class);
            if (!starLiveChatModel.getUid().equals(getUid()) || !mIsLive) {
                Message msg = mHandler.obtainMessage(CHAT_STAR_LIVE_END, starLiveChatModel);
                mHandler.sendMessage(msg);
            }
        } else if (ChatData.CHAT_TYPE_LIVE_PAUSE == chatData.getType()) {
            //先注释,收到中断推流消息不显示小人
//            StarLiveChatModel starLiveChatModel = JSON.parseObject(data.getDatas(), StarLiveChatModel.class);
//            if (!starLiveChatModel.getUid().equals(getUid()) || !mIsLive) {
//                Message msg = mHandler.obtainMessage(CHAT_STAR_LIVE_PAUSE, starLiveChatModel);
//                mHandler.sendMessage(msg);
//            }
        } else if (ChatData.CHAT_TYPE_JOIN_IN_ICON == chatData.getType()) {
            updateJoin(chatData.getUuid(), chatData.getAvatar());
        } else if (ChatData.CHAT_TYPE_SYSTEM_MSG == chatData.getType()) {
            Message msg = mHandler.obtainMessage(CHAT_SYSTEM_MSG, chatData);
            mHandler.sendMessage(msg);
        }else if(ChatData.CHAT_TYPE_BUY_GUARD == chatData.getType())
        {
            if(mStarLiveModel != null && mStarLiveModel.getStarModel() != null){
                chatModle = chatData.toCharModelByGrund(mStarLiveModel.getStarModel().getNickName());
                sendMsg(chatModle);

                //刷新人气值
                Message msg = mHandler.obtainMessage(CHAT_UPDATE_HOT_VALUE, chatData);
                mHandler.sendMessage(msg);
            }
        }
    }


    @Override
    public void sendContent(ChatData chatdata) {
        //回显自己发送的聊天内容
        sendMsg(chatdata.toChatModle());
    }

    public void sendMsg(ChatDataModel chatModle) {
        if (chatModle != null) {
            if (!mIsMsgReminderOn) {
                mIsMsgReminderOn = true;
            }
            Message msg = mHandler.obtainMessage(CHAT_NNOTIFY, chatModle);//聊天室消息
            mHandler.sendMessage(msg);
        }
    }

    @Override
    public void connectionSuccess() {
        sendGuardMessage();
    }

    @Override
    public void notifyList() {
        if (mChatListAdapter != null) {
            mChatListAdapter.notifyDataSetChanged();
            switchReminder();
        }
    }

    @Override
    public void ok() {
        if (!StringUtil.isNullorEmpty(getMqttClientId())) {
            mIsLiveEnd = true;
            liveStatusNotify("7");//直播停止
        }
        StarLiveChatModel starLiveChatModel = new StarLiveChatModel();
        starLiveChatModel.setHots((mHotCurr - mHot) + "");
        starLiveChatModel.setOnline(mMaxOnLine + "");
        starLiveChatModel.setLiveTime(mTvName.getText().toString());

        Message msg = mHandler.obtainMessage(CHAT_STAR_LIVE_END, starLiveChatModel);
        mHandler.sendMessageDelayed(msg, 1000);
    }

    @Override
    public void cancle() {

    }

    @Override
    public void onCompletion(IMediaPlayer mp) {
        if (mPopupWindowPause != null && mPopupWindowPause.getVisibility() == View.VISIBLE) {
            mPopupWindowPause.setVisibility(View.GONE);
        }
        showOfflinePopupwindow();
    }

    @Override
    public boolean onError() {
        if (mPopupWindowPause != null && mPopupWindowPause.getVisibility() == View.VISIBLE) {
            mPopupWindowPause.setVisibility(View.GONE);
        }
        showOfflinePopupwindow();
        return false;
    }

    @Override
    public void onPrepared(IMediaPlayer mp) {
        if (mPopupWindowPause != null) {
            mPopupWindowPause.setVisibility(View.GONE);
        }
        if (mPopupWindowOffline != null) {
            mPopupWindowOffline.setVisibility(View.GONE);
        }
    }

    @Override
    public void onVideoPuse() {
        synchronized (obj){
            if (mPopupWindowOffline != null && mPopupWindowOffline.getVisibility() == View.VISIBLE) {
                return;
            }
            if (mPopupWindowPause != null && mPopupWindowPause.getVisibility() != View.VISIBLE) {
                mPopupWindowPause.setVisibility(View.VISIBLE);
            } else if (mPopupWindowPause == null) {
                showPausePopupwindow();
            }
        }
    }

    @Override
    public void onVideoResum() {
        synchronized (obj){
            if (mPopupWindowPause != null) {
                mPopupWindowPause.setVisibility(View.GONE);
            }
            if (mPopupWindowOffline != null) {
                mPopupWindowOffline.setVisibility(View.GONE);
            }
        }
    }

    @Override
    public void hasSend() {
        mIbtnGift.setVisibility(View.VISIBLE);
        mViewBottom.setVisibility(View.VISIBLE);
    }


    @Override
    public void onUpdatePushUrl() {

    }

    @Override
    public void onAuthFailure() {

    }

    @Override
    public void onStarLiveError() {
        showLiveErrorPopupwindow();
    }

    @Override
    public void onStarLiveStart() {
        if (mPopupWindowError != null) {
            mPopupWindowError.setVisibility(View.GONE);
        }
        mIsStartUpLive = true;

        if(mCountTime == 0){//首次拉流直播开始，通知服务器直播开始
            //开始计时
            mHandler.sendEmptyMessageDelayed(WHAT_LIVE_COUNT, mDelayTime);
            liveStatusNotify("-1");
        }
    }

    @Override
    public void finish() {
        getMqtt().stopMQTTService();
        super.finish();
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (mFlakeView != null && mViewPager.getCurrentItem() != 0 && event.getAction() == MotionEvent.ACTION_UP) {
            mFlakeView.onClick();
        }
        return false;
    }

}
